package cn.sale.tool;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class OperationFileTool {
	
	private BufferedReader reader = null;
	
	private BufferedWriter writer = null;
	
	private File file = null;
	
	public OperationFileTool(String filePath)throws IOException{
		String fileDir = filePath.substring(0, filePath.lastIndexOf(File.separator));
		File dirstory = new File(fileDir);
		if(!dirstory.exists() || !dirstory.isDirectory()) {
			dirstory.mkdirs();
		}
		file = new File( filePath );
		if( !file.exists() || !file.isFile()) {
			file.createNewFile();
		}
	}
	
	
	public String getLine() throws IOException{
		if( reader == null ) {
			reader = new BufferedReader( new InputStreamReader(
					new FileInputStream( file ), "UTF-8") );
		}
		return reader.readLine();
	}
	
	public void writerInfo(String message) throws IOException{
		if( writer == null ) {
			writer = new BufferedWriter( new OutputStreamWriter( 
					new FileOutputStream( file , false) ,"UTF-8") );
		}
		writer.write(message);
		writer.newLine();
		writer.flush();
	}
	
	public void writerInfo(Object obj) throws IOException {
		this.writerInfo( String.valueOf( obj ) );
	}
	
	public void close() throws IOException {
		if(reader != null) {
			reader.close();
		}
		
		if(writer != null) {
			writer.flush();
			writer.close();
		}
	}
	
}
